<script setup lang="ts">
import { ref } from 'vue'
import type { ListResultData } from '@/api/base'
import { ElMessage } from 'element-plus'
import {
  type BlogAndTagResult,
  type addOrUpdateBlogDto,
  addOrUpdateBlogItem,
  deleteBlogItem,
  getBlogs
} from '@/api/blog'

import AddEditBlogDialog from './components/AddEditBlogDialog.vue'
import { getSystemColor } from '@/utils/cache'
// import { Message } from '@element-plus/icons-vue'

interface filterFormObj {
  key?: string
  blogType: number
}
const addEditDialogTitle = ref('')
const loading = ref(false)
const addEditBlogDialog = ref<InstanceType<typeof AddEditBlogDialog>>()
const filterForm = ref<filterFormObj>({ key: '', blogType: 1 })
const currentRow = ref<BlogAndTagResult | undefined>(undefined)
const isEditInfo = ref(false)
const pager = ref({
  page: 1,
  size: 20
})
const articlesData = ref({
  mode: 'config',
  data: { list: [] as any[], total: 0 },
  auto: true,
  isPager: true,
  columns: [
    { label: 'id', prop: 'id', width: '70' },
    { label: '文章标题', prop: 'blogTitle', minWidth: '100' },
    { label: '标签', prop: 'tagList', slot: true, minWidth: '140' },
    { label: '状态', prop: 'enable', slot: true, width: '90' },
    { label: '创建时间', prop: 'createDate', width: '166' },
    { label: '更新时间', prop: 'updateDate', width: '166' },
    { label: '操作', fixed: 'right', prop: 'actions', width: '166', slot: true }
  ],
  index: true
})
// 接口请求
// 说明： 设置 auto = true, callback = getTableDataFn 当切换分页时，自动调用 callback 回调
const getTableDataFn = async () => {
  loading.value = true
  const res = await getBlogs({
    key: filterForm.value?.key || '',
    blogType: filterForm.value.blogType,
    ...pager.value
  })
  loading.value = false
  if (res && res.code === 200) {
    // const data = res.data as BlogAndTagResult[]
    const resInfo = res.data as ListResultData<BlogAndTagResult[]>
    articlesData.value.data = resInfo as ListResultData<BlogAndTagResult[]>
  } else {
    ElMessage({ message: res?.msg || '网络异常，请稍后重试', type: 'error' })
  }
}
function editBlogHandler(row: BlogAndTagResult) {
  addEditBlogDialog.value!.openDialog()
  isEditInfo.value = true
  addEditDialogTitle.value = '修改文章信息'
  currentRow.value = { ...row }
}
function deleteBlogItemHandler(row: BlogAndTagResult) {
  loading.value = true
  deleteBlogItem(row.id)
    .then((res) => {
      console.log(res)
      ElMessage.success(res.msg)
      getTableDataFn()
    })
    .finally(() => {
      loading.value = false
    })
}
// 新增标签
function addTagHandler() {
  currentRow.value = undefined
  isEditInfo.value = false
  addEditBlogDialog.value!.openDialog()
  addEditDialogTitle.value = '新增文章'
}
function updateEnableHandler(row: BlogAndTagResult) {
  loading.value = true
  addOrUpdateBlogItem({
    ...row,
    id: row.id,
    createDate: undefined,
    updateDate: undefined,
    tagList: (row.tagsList || []).map((v) => v.id),
    tagsList: undefined,
    actions: undefined
  } as addOrUpdateBlogDto)
    .then((res) => {
      console.log(res)
      ElMessage.success(res.msg)
      getTableDataFn()
    })
    .finally(() => {
      loading.value = false
    })
}
</script>

<template>
  <div class="my-page-container box-bg-color">
    <div class="my-page-main">
      <div class="my-filter-form">
        <div class="my-top-title">
          <span class="my-primary-title">文章管理</span>
          <div class="my-top-btns">
            <el-button type="primary" @click="addTagHandler">新增</el-button>
          </div>
        </div>
        <el-divider></el-divider>
        <el-form :model="filterForm" inline>
          <el-form-item label="查询条件">
            <el-input
              v-model="filterForm.key"
              placeholder="标签名/描述"
              @keydown.enter.prevent="getTableDataFn"
            ></el-input>
          </el-form-item>
          <el-form-item label="文章类型">
            <el-radio-group v-model="filterForm.blogType" @change="getTableDataFn">
              <el-radio :value="1">博客文章</el-radio>
              <el-radio :value="2">新闻趣事</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-button class="at-fr" @click="getTableDataFn">查询</el-button>
        </el-form>
      </div>
      <div class="my-main-content">
        <k-table
          ref="userTableRef"
          v-bind="articlesData"
          :callback="getTableDataFn"
          :loading="loading"
          border
          stripe
          current-row-key="id"
          style="width: 100%"
        >
          <template #enable="{ row }">
            <!--            <k-badge-->
            <!--              :type="row.enable === true ? 'success' : 'danger'"-->
            <!--              :articles="row.enable === true ? '可用' : '不可用'"-->
            <!--            ></k-badge>-->
            <el-switch v-model="row.enable" @change="updateEnableHandler(row)"></el-switch>
          </template>
          <template #tagList="{ row }">
            <!--            <k-badge-->
            <!--              :type="row.enable === true ? 'success' : 'danger'"-->
            <!--              :articles="row.enable === true ? '可用' : '不可用'"-->
            <!--            ></k-badge>-->
            <template v-for="(item, index) in row.tagsList" :key="item.id">
              <el-tag effect="dark" style="margin-right: 4px" round :color="getSystemColor(index)">{{
                item.tagName
              }}</el-tag>
            </template>
          </template>
          <template #actions="{ row }">
            <el-button type="primary" plain @click="editBlogHandler(row)">修改</el-button>
            <el-popconfirm
              title="确定要删除吗？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="deleteBlogItemHandler(row)"
            >
              <template #reference>
                <el-button type="danger" plain>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </k-table>
      </div>
    </div>
    <AddEditBlogDialog
      :title="addEditDialogTitle"
      ref="addEditBlogDialog"
      :current-data="currentRow"
      :is-edit="isEditInfo"
      :blogType="filterForm.blogType"
      @handle-refresh="getTableDataFn"
    ></AddEditBlogDialog>
  </div>
</template>

<style scoped lang="scss">
.my-page-main {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  height: 100%;
  .my-filter-form {
    flex: 1 1 100px;
    .my-top-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      & > span {
        font-size: 18px;
      }
    }
  }
  .my-main-content {
    flex: 1 1 calc(100% - 100px);
    overflow: hidden;
    .k-table-container {
      height: 100%;
      ::v-deep(.k-table__inner) {
        height: 100%;
      }
    }
  }
}
</style>
